
package com.bangcommunity.bbframe.http;

import com.bangcommunity.bbframe.http.interceptor.RestInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author tanghc
 */
public class HttpApiClient {

    static Logger logger = LoggerFactory.getLogger(HttpApiClient.class);
    private Retrofit retrofit = null;
    private static ConcurrentHashMap<HttpApiConfig, HttpApiClient> serviceCache = new ConcurrentHashMap<>();

    private HttpApiClient() {
    }

    public static synchronized HttpApiClient getInstance(HttpApiConfig config) {

        HttpApiClient instance = serviceCache.get(config);
        if (instance == null) {
            instance = new HttpApiClient();
            instance.init(config);
            serviceCache.putIfAbsent(config, instance);
        }
        return instance;
    }

    /**
     * 初始化客户端上下文
     */
    private void init(HttpApiConfig config) {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String s) {
                logger.info(s);
            }
        });
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(httpLoggingInterceptor);
        if (config.isRest()) {
            builder.addInterceptor(new RestInterceptor());
        }
        OkHttpClient client = builder.build();
        retrofit = new Retrofit.Builder().baseUrl(config.getServerUri()).client(client)
                .addConverterFactory(GsonConverterFactory.create()).build();
    }

    /**
     * 构造对象
     * 
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> T buildService(Class<T> tClass) {
        return retrofit.create(tClass);
    }

}
